import { SyntheticEvent } from "react";
import { IRgba, RGBA } from "./QrCode/typing";


// 阻止冒泡
export function stopPropagation(e: SyntheticEvent) {
  e.stopPropagation();
  e.nativeEvent.stopPropagation();
}


export function RGBAToString(RGBA: RGBA) {
  const { r, g, b, a = 1 } = RGBA;
  if (a !== undefined) {
    return `rgba(${r},${g},${b},${a})`;
  }
  return `rgba(${r},${g},${b})`;
}

export function RGBAToStringByOpacity(RGBA: RGBA, opacity: number) {
  const { r, g, b } = RGBA;
  return `rgba(${r},${g},${b},${opacity})`;
}

export function RGBStringToOBJ(RGB: string) {
  const rgb = RGB.replace(/[^\d,]/g, '').split(',');
  const tempColor = {
    r: Number(rgb[0]),
    g: Number(rgb[1]),
    b: Number(rgb[2]),
    a: 1,
  };

  return tempColor
}
export function angleCanvasToDom(angle: number) {
  return 90 - angle;
}


// 十进制转化为16进制
export function hex(n: number) {
  return `0${n.toString(16)}`.slice(-2);
}

/**
 * rbga对象转化为16进制颜色字符串
 * @param rgba
 * @returns
 */
export const rbgaObjToHex = (rgba: RGBA) => {
  let { r, g, b } = rgba;
  const { a = 1 } = rgba;
  r = Math.floor(r * a);
  g = Math.floor(g * a);
  b = Math.floor(b * a);
  return `#${hex(r)}${hex(g)}${hex(b)}`;
};


// linear-gradient(90deg, rgb(255, 255, 255) 0%, rgb(248, 202, 107) 0%, rgb(252, 174, 125) 59.2593%, rgb(252, 174, 125) 60.4938%);
export function getBackgroundByEffect(effData: any) {
  const data = JSON.parse(JSON.stringify(effData));
  data.colorStops.sort((a: any, b: any) => {
    return a.offset - b.offset;
  });
  data.angle = angleCanvasToDom(data.angle);
  let temp = `linear-gradient(${data.angle}deg,`;
  data.colorStops.forEach((element: any, index: any) => {
    let setColor = element.color;
    if (setColor) {
      if (typeof setColor !== 'string') {
        setColor = RGBAToString(setColor);
      }
      if (index === data.colorStops.length - 1) {
        temp = `${temp + setColor} ${element.offset * 100}%`;
      } else {
        temp = `${temp + setColor} ${element.offset * 100}%,`;
      }
    }
  });
  temp += ')';
  return temp;
}


export function colorToRGBAObject(color: string) {
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  console.log(reg.test(color));

  if (color && reg.test(color)) {
    color = color.toLowerCase();
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      let colorNew = '#';
      for (let i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
      color = colorNew;
    }
    const rbga = [];
    for (let i = 1; i < 7; i += 2) {
      rbga.push(parseInt(`0x${color.slice(i, i + 2)}`));
    }
    return { r: rbga[0], g: rbga[1], b: rbga[2], a: 1 };
  }
  return {};
}

